package com.zl.protocol.des;

/**
 * 用于处理PBOC的3DES和MAC算法
 *
 * @author lxt_team on 2020-03-09 17:36:00
 */
public class DesHelperV2 extends DesHelper {

    public DesHelperV2() {
        super();
    }


    // //////////////////////////////////////////////////////////////////////////////////////////////
    // 以下是李工设备历史调用接口
    public String PBOC_3DES_MAC_discryption(String data, String key) {
        String vector = "0000000000000000"; // 初始向量0000000000000000
        if (key.length() != 32) {
            return null;
        }

        int len = data.length();
        int arrLen = len % 16 == 0 ? len / 16 : len / 16 + 1;
        String[] D = new String[arrLen];
        if (len % 16 == 0) {
            data += "8000000000000000";
        } else {
            data += "80";
            for (int i = 0; i < 15 - len % 16; i++) {
                data += "00";
            }
        }
        for (int i = 0; i < arrLen; i++) {
            D[i] = data.substring(i * 16, i * 16 + 16);
        }

        // D0 Xor Vector
        String I = xOr(D[0], vector);
        String O = null;
        String kl = key.substring(0, 16);
        for (int i = 1; i < arrLen; i++) {
            O = DES_1(I, kl, 0);
            I = xOr(D[i], O);
        }
        I = DES_3(I, key, 1);
        return I;

    }

    /**
     * DES3_AA 补AA
     *
     * @param data 长度不能被16整除则补数据，按AA补
     * @param key  长度密码为32个HEX码
     * @param type 0:encrypt 1:discrypt
     * @return 返回3DES的结果值
     */
    private String DES3_AA(String data, String key, int type) {
        if (key.length() != 32) {
            return null;
        }

        int len = data.length();
        int arrLen = len % 16 == 0 ? len / 16 : len / 16 + 1;
        String[] D = new String[arrLen];
        if (len % 16 != 0) {
            data += "AA";
            for (int i = 0; i < 15 - len % 16; i++) {
                data += "AA";
            }
        }
        for (int i = 0; i < arrLen; i++) {
            D[i] = data.substring(i * 16, i * 16 + 16);
        }


        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arrLen; i++) {
            sb.append(DES_3(D[i], key, type));
        }
        return sb.toString();
    }

    public String PBOC_3DES_AA(String data, String key) {
        return DES3_AA(data, key, 0);/*000000010000000003E8FFFFFFFF,A597B3DAD17DBC89FFFFFFFF1BB71CEF*/
    }

    public String PBOC_3DES_discryption_AA(String data, String key) {
        return DES3_AA(data, key, 1);
    }


}
